package com.example.wx.dailyreport.controller.security.filter;


import com.example.wx.dailyreport.customtool.JWTTool;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(JWTTool.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JWTTool.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader, response));
        super.doFilterInternal(request, response, chain);
    }

    // 这里从token中获取用户信息,如果token快失效时，返回一个新token
    private Authentication getAuthentication(String tokenHeader, HttpServletResponse response) {
        String token = tokenHeader.substring(JWTTool.TOKEN_PREFIX.length());
        Map<String, Object> map = JWTTool.getMapByJwt(token);
        try {
            String username = (String) map.get(JWTTool.JWT_USERNAME);
            String role = (String) map.get(JWTTool.JWT_ROLE);
            Set<GrantedAuthority> set = new HashSet<>();
            set.add(new SimpleGrantedAuthority(role));
            Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, set);

            if (JWTTool.getExpiresDateByJwt(token) - System.currentTimeMillis() < JWTTool.MINTIME) {
                Map<String, Object> headmap = new LinkedHashMap<>();
                headmap.put(JWTTool.JWT_USERNAME, authentication.getPrincipal());
                headmap.put(JWTTool.JWT_ROLE, new LinkedList<>(authentication.getAuthorities()).getFirst().toString());
                String newtoken = JWTTool.createJwt(headmap);
                response.setHeader(JWTTool.TOKEN_HEADER, JWTTool.TOKEN_PREFIX + newtoken);
            }
            return authentication;
        } catch (Exception e) {
            return null;
        }
    }


}
